package com.xiaoyang.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoyang.forum.common.code.Result;
import com.xiaoyang.forum.common.code.ResultCode;
import com.xiaoyang.forum.common.exception.ApplicationException;
import com.xiaoyang.forum.domain.dto.MessageDTO;
import com.xiaoyang.forum.domain.pojo.Message;
import com.xiaoyang.forum.domain.pojo.User;
import com.xiaoyang.forum.domain.vo.MessageVO;
import com.xiaoyang.forum.mapper.MessageMapper;
import com.xiaoyang.forum.mapper.UserMapper;
import com.xiaoyang.forum.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author XiaoYang
 * @since 2025-08-23
 */
@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 发送消息
     * @param messageDTO
     * @return
     */
    @Override
    public int sendMessage(MessageDTO messageDTO) {
        // 1. 根据用户id查询用户信息
        User user = userMapper.selectById(messageDTO.getSendUserId());
        if (user == null) {
            log.info("用户不存在" + messageDTO.getSendUserId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        if (user.getState() == 1) {
            // 用户已被禁言
            log.info("用户已被禁言" + messageDTO.getSendUserId());
            return 0;
        }

        // 2. 查询接收方是否存在
        User receiveUser = userMapper.selectById(messageDTO.getReceiveUserId());
        if (receiveUser == null) {
            log.info("接收方不存在" + messageDTO.getReceiveUserId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 3. 发送消息
        Message message = new Message();
        message.setPostUserId(messageDTO.getSendUserId());
        message.setReceiveUserId(messageDTO.getReceiveUserId());
        message.setContent(messageDTO.getContent());
        message.setState(0); // 未读
        message.setCreateTime(LocalDateTime.now());
        message.setUpdateTime(LocalDateTime.now());

        return messageMapper.insert(message);
    }

    /**
     * 获取未读消息数量
     * @param userId
     * @return
     */
    @Override
    public Long getUnreadCount(long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            log.info("用户不存在" + userId);
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // select count(0) from t_message where state = 0 and receive_user_id = 19;
        return messageMapper.selectCount(new LambdaQueryWrapper<Message>()
                .eq(Message::getState, 0)
                .eq(Message::getReceiveUserId, userId));
    }

    /**
     * 获取未读消息列表
     * @param receiveUserId
     * @return
     */
    @Override
    public List<MessageVO> toList(long receiveUserId) {
        User user = userMapper.selectById(receiveUserId);
        if (user == null) {
            log.info("用户不存在" + receiveUserId);
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        return messageMapper.toList(receiveUserId);
    }

    /**
     * 修改消息状态
     * @param id
     * @param userId
     * @return
     */
    @Override
    public Integer updateState(Long id, long userId) {
        if (id == null) {
            log.info("消息id不能为空");
            throw new ApplicationException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            log.info("用户不存在" + userId);
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 查询消息信息
        Message message = messageMapper.selectById(id);
        if (message == null) {
            log.info("消息不存在" + id);
            throw new ApplicationException(Result.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }

        // 校验信息接收人是否为当前用户
        if (message.getReceiveUserId() != userId) {
            log.info("用户无权限修改消息" + userId);
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NO_PERMISSION));
        }
        message.setState(1);

        return messageMapper.updateById(message);
    }

    /**
     * 回复消息
     * @param messageDTO
     * @return
     */
    @Override
    public int reply(MessageDTO messageDTO) {
        log.info("回复消息");
        // 当前登录用户
        User user = userMapper.selectById(messageDTO.getSendUserId());
        if (user == null) {
            log.info("用户不存在" + messageDTO.getSendUserId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if (user.getState() == 1) {
            // 用户已被禁言
            log.info("用户已被禁言" + messageDTO.getSendUserId());
            return 0;
        }

        // 接收方
        Message message = messageMapper.selectById(messageDTO.getId());
        if (message == null) {
            log.info("消息不存在" + messageDTO.getId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }
        // 判断是否为接收方
        if (!message.getReceiveUserId().equals(messageDTO.getSendUserId())) {
            log.info("用户无权限回复消息" + messageDTO.getSendUserId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NO_PERMISSION));
        }

        User PostUser = userMapper.selectById(message.getPostUserId());
        if (PostUser == null) {
            log.info("用户不存在" + message.getPostUserId());
            throw new ApplicationException(Result.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        Message replyMessage = new Message();
        replyMessage.setPostUserId(user.getId());
        replyMessage.setContent(messageDTO.getContent());
        replyMessage.setReceiveUserId(PostUser.getId());
        replyMessage.setState(0);
        replyMessage.setCreateTime(LocalDateTime.now());
        replyMessage.setUpdateTime(LocalDateTime.now());

        // 修改回复消息的状态
        message.setState(2);
        messageMapper.updateById(message);
        log.info("修改回复消息状态成功" + message.getId());

        log.info("回复消息成功" + replyMessage.getId());
        return messageMapper.insert(replyMessage);
    }
}
